const express = require('express')
const { getUserInfo } = require('../utils/permission')
const User = require('../models/User')
const router = express.Router()

/**
 * 根据 token 获取用户的购物车数据
 */
router.get('/', (req, res) => {
  const user = getUserInfo(req)
  User
    .find({phone: user?.phone}, 'cart')
    .then(data => {
      const cart = data[0]?.cart
      res.json({
        code: 200,
        data: {
          cart
        }
      })
    })
})

/**
 * 保存购物车商品信息
 */
router.put('/', (req, res) => {
  const user = getUserInfo(req)
  if (user) {
    const { cart } = req.body
    // cart && Array.isArray(cart) && cart.forEach(item => {
    //   if (!item.initPrice) {
    //     item.initPrice = item.price
    //   }
    // })
    User
      .updateOne({phone: user.phone}, {cart})
      .then(() => {
        res.json({
          code: 200,
          data: {
            message: '更新成功'
          }
        })
      })
  } else {
    res.json({
      code: 200,
      data: {
        message: '没有用户信息'
      }
    })
  }
})

module.exports = router
